package com.agent.service.mail.impl;

import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import java.util.Properties;

/**
 * Created by hg on 2019/1/31.
 */
public class GmailImap {
    private static final String email_id = "xutao6936@gmail.com";
    private static final String password = "xutao63935936";

    public static void main(String[] args) {


        //set properties
        Properties properties = new Properties();
        //You can use imap or imaps , *s -Secured
        properties.put("mail.store.protocol", "gimaps");
        //Host Address of Your Mail
        properties.put("mail.imaps.host", "imap.gmail.com");
        //Port number of your Mail Host
        properties.put("mail.imaps.port", "993");

        //properties.put("mail.imaps.timeout", "10000");

        try {

            //create a session
            Session session = Session.getDefaultInstance(properties, null);
            //SET the store for IMAPS
            Store store = session.getStore("gimaps");

            System.out.println("Connection initiated......");
            //Trying to connect IMAP server
            store.connect(email_id, password);
            System.out.println("Connection is ready :)");


            //Get inbox folder
            Folder inbox = store.getFolder("inbox");
            //SET readonly format (*You can set read and write)
            inbox.open(Folder.READ_ONLY);


            //Display email Details

            //Inbox email count
            int messageCount = inbox.getMessageCount();
            System.out.println("Total Messages in INBOX:- " + messageCount);

            //Print Last 10 email information
            for (int i = 10; i > 0; i--) {
                System.out.println("Mail Subject:- " + inbox.getMessage(messageCount - i).getSubject());
                System.out.println("Mail From:- " + inbox.getMessage(messageCount - i).getFrom()[0]);
                System.out.println("Mail Content:- " + inbox.getMessage(messageCount - i).getContent().toString());
                System.out.println("------------------------------------------------------------");
            }

            inbox.close(true);
            store.close();

        } catch (Exception e) {
            e.printStackTrace();
        }




    }
}
